import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class IntoServlet01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        //获取表单中下拉选项框选和文本框输入的值中的值
        String name=request.getParameter("JC");
        System.out.println(name);
        String amount=request.getParameter("amount");
        System.out.println(amount);
        Connection conn=null;
        PreparedStatement ps=null;
        int count=0;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://localhost/jcdb","root","19970913Xun");
            //关闭自动提交机制
            conn.setAutoCommit(false);
            String sql="update t_jcamount set amount=amount+? where name=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,amount);
            ps.setString(2,name);
            count=ps.executeUpdate();
            //提交事务
            conn.commit();
        } catch (ClassNotFoundException e) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        //判断修改成功重定向至提示成功页面
        if(count==1){
            response.sendRedirect(request.getContextPath()+"/IntoSuccess.html");
        }
    }
}
